package com.tencent.elife.utils;

import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

/**
 * @author zijianlu
 * @version 创建时间：2011-12-30 下午7:44:05 类说明
 */
public class DataRequireTask<T> extends AsyncTask<Object, Object, ArrayList<T>> {
    private volatile boolean cancelFlg;

    private UICallBack<T> mCallBack;

    private Handler mHandler;

    public DataRequireTask(UICallBack<T> callBack, Context context) {
        this.mCallBack = callBack;
        cancelFlg = false;
        mHandler = new Handler(context.getMainLooper());
    }

    @Override
    protected void onPreExecute() {
        if (!cancelFlg && mCallBack != null) {
            mCallBack.onBegin();
        }
    }

    @Override
    protected void onCancelled() {
        cancelFlg = true;
        if (mCallBack != null) {
            mCallBack.onCancel();
        }
    }

    @Override
    protected ArrayList<T> doInBackground(Object... params) {
        if (!cancelFlg && mCallBack != null) {
            try {
                return mCallBack.doRun();
            } catch (final Exception e) {
                cancelFlg = true;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mCallBack.onException(e);
                    }
                });
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<T> result) {
        if (!cancelFlg && mCallBack != null) {
            mCallBack.onComplete(result);
        }
    }

    public interface UICallBack<T> {
        public void onBegin();

        public ArrayList<T> doRun() throws Exception;

        public void onCancel();

        public void onComplete(ArrayList<T> data);

        public void onException(Exception e);
    }
}
